import { useState, type FormEvent } from 'react'

interface RegisterFormProps {
  onSuccess?: (user: any, token: string) => void
  onSwitchToLogin?: () => void
}

interface RegisterData {
  username: string
  email: string
  password: string
  confirmPassword: string
}

interface ApiResponse {
  code: number
  message: string
  data?: {
    user?: any
    token?: string
  }
  error?: string
}

export default function RegisterForm({ onSuccess, onSwitchToLogin }: RegisterFormProps) {
  const [formData, setFormData] = useState<RegisterData>({
    username: '',
    email: '',
    password: '',
    confirmPassword: ''
  })
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  const validateForm = (): string | null => {
    if (formData.username.length < 3 || formData.username.length > 50) {
      return '用户名长度必须在3-50字符之间'
    }
    if (formData.password.length < 6) {
      return '密码长度至少6位'
    }
    if (formData.password !== formData.confirmPassword) {
      return '两次输入的密码不一致'
    }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      return '请输入有效的邮箱地址'
    }
    return null
  }

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault()
    setError('')

    const validationError = validateForm()
    if (validationError) {
      setError(validationError)
      return
    }

    setLoading(true)

    try {
      const response = await fetch('http://localhost:8080/api/v1/auth/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          username: formData.username,
          email: formData.email,
          password: formData.password
        }),
      })

      const data: ApiResponse = await response.json()

      if (data.code === 1 && data.data && data.data.user && data.data.token) {
        // 保存token到localStorage
        localStorage.setItem('auth_token', data.data.token)
        localStorage.setItem('user', JSON.stringify(data.data.user))
        
        if (onSuccess) {
          onSuccess(data.data.user, data.data.token)
        }
      } else {
        setError(data.error || data.message || '注册失败')
      }
    } catch (err) {
      setError('网络错误，请稍后重试')
    } finally {
      setLoading(false)
    }
  }

  const handleInputChange = (field: keyof RegisterData, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }))
  }

  return (
    <div className="card" style={{ maxWidth: '400px', margin: '0 auto' }}>
      <div className="card-header">
        <h2 className="card-title text-center">注册</h2>
        <p className="card-description text-center">加入 AI Prompt Hub 社区</p>
      </div>
      <div className="card-content">
        <form onSubmit={handleSubmit} className="space-y-3">
          {error && (
            <div className="p-3 bg-red-50 border border-red-200 rounded-md">
              <p className="text-red-600 text-sm">{error}</p>
            </div>
          )}
          
          <div>
            <label htmlFor="username" className="block text-sm font-medium mb-1">
              用户名
            </label>
            <input
              id="username"
              type="text"
              required
              className="input"
              placeholder="请输入用户名（3-50字符）"
              value={formData.username}
              onChange={(e) => handleInputChange('username', e.target.value)}
            />
          </div>

          <div>
            <label htmlFor="email" className="block text-sm font-medium mb-1">
              邮箱地址
            </label>
            <input
              id="email"
              type="email"
              required
              className="input"
              placeholder="请输入邮箱地址"
              value={formData.email}
              onChange={(e) => handleInputChange('email', e.target.value)}
            />
          </div>

          <div>
            <label htmlFor="password" className="block text-sm font-medium mb-1">
              密码
            </label>
            <input
              id="password"
              type="password"
              required
              className="input"
              placeholder="请输入密码（至少6位）"
              value={formData.password}
              onChange={(e) => handleInputChange('password', e.target.value)}
            />
          </div>

          <div>
            <label htmlFor="confirmPassword" className="block text-sm font-medium mb-1">
              确认密码
            </label>
            <input
              id="confirmPassword"
              type="password"
              required
              className="input"
              placeholder="请再次输入密码"
              value={formData.confirmPassword}
              onChange={(e) => handleInputChange('confirmPassword', e.target.value)}
            />
          </div>

          <button
            type="submit"
            disabled={loading}
            className={`btn btn-primary w-full ${loading ? 'opacity-50 cursor-not-allowed' : ''}`}
          >
            {loading ? '注册中...' : '注册'}
          </button>
        </form>

        <div className="mt-4 text-center">
          <p className="text-sm text-muted">
            已有账号？{' '}
            <button
              type="button"
              onClick={onSwitchToLogin}
              className="text-primary hover:underline"
            >
              立即登录
            </button>
          </p>
        </div>
      </div>
    </div>
  )
}